package com.cherry.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cherry.common.exception.ServiceException;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 根据城市获取省份名
 *
 * @Author: 孙晨阳
 * @Date: 2023/3/13 14:56
 * @Version 1.0
 */
public class ProvinceUtils {

    private static final InputStream PROVINCIAL_DATA = ProvinceUtils.class.getClassLoader().getResourceAsStream("myCity.json");

    private static final JSONObject PROVINCES_JSON;

    public static final Map<String, Integer> PROVINCES_MAP = new HashMap<>(34);

    /**
     * 初始化各省份岗位数量Map集合
     */
    static {
        if (PROVINCIAL_DATA == null) {
            throw new ServiceException("未读取到json文件！");
        }
        PROVINCES_JSON = readJsonFile(PROVINCIAL_DATA);

        Set<String> provincesRawData = PROVINCES_JSON.keySet();

        Set<String> provincesData = provincesRawData.stream().map(p -> p.replace("省", "")).collect(Collectors.toSet());

        provincesData.forEach(p -> PROVINCES_MAP.put(p, 0));
    }

    /**
     * 根据城市获取省份
     *
     * @param city 城市
     * @return 省份
     */
    public static String getProvinceByCity(String city) {
        if (city.length() < 2) {
            return null;
        }

        if (PROVINCIAL_DATA == null) {
            throw new ServiceException("未读取到json文件！");
        }

        for (String s : PROVINCES_JSON.keySet()) {
            JSONArray jsonArray = PROVINCES_JSON.getJSONArray(s);
            for (int i = 0; i < jsonArray.size(); i++) {
                if (jsonArray.getString(i).contains(city)) {
                    return s.replace("省", "");
                }
            }
        }
        return null;
    }

    /**
     * 将输入流准换为JSONObject
     *
     * @param inputStream 输入流
     * @return JSONObject
     */
    public static JSONObject readJsonFile(InputStream inputStream) {
        StringBuilder strResponse = new StringBuilder();
        String strMessage = "";
        BufferedReader reader;
        reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        while (true) {
            try {
                if ((strMessage = reader.readLine()) == null) {
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            strResponse.append(strMessage);
        }
        try {
            reader.close();
            inputStream.close();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        String str = strResponse.toString();
        return JSON.parseObject(str);
    }

}

